/**
 * Copyright ©2012-2018 HopeHaiyang Corporation, All Rights Reserved
 * http://www.wuhanhope.com
 */
package hope.platform.data.web.base;

import hope.platform.data.server.function.header.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * class info
 *
 * @author hujia
 *         Create at 2018/7/13 14:29
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @RequestMapping(value = "/multipleFileUpload", method = RequestMethod.POST)
    public List<String> MultipleFileUpload(@RequestParam("file") MultipartFile[] files) {
        String fileName = null;
        List<String> results = new ArrayList<>();
        String result;
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                try {
                    fileName = files[i].getOriginalFilename();
                    result = fileService.saveFile(files[i]);
                } catch (Exception e) {
                    result = "You failed to upload " + fileName;
                }
                results.add(result);
            }
        } else {
            result = "Unable to upload. File is empty.";
            results.add(result);
        }
        return results;
    }

    @RequestMapping(value = "fileUrl", method = RequestMethod.DELETE)
    public String DeleteFile(@RequestParam String fileUrl) {
        fileService.deleteFile(fileUrl);
        return "ok";
    }
}
